{extend name="$_admin_public_base_"/}
  {block name="style"}
    <link href="__LIBS__/webuploader/css/webuploader.css" type="text/css" rel="stylesheet">
    <link href="__LIBS__/daterangepicker/daterangepicker-bs3.css" type="text/css" rel="stylesheet">
    <style type="text/css">
    #more-method{display: none;}
    .meta-ext{background-color: #55CCFF;color:#fff;font-size: 12px;font-weight:500;padding:0px 8px 2px;float: right;border-radius: 2px;}
    .attachment-foot .file-name{white-space:nowrap;width:63%;padding-left: 3px;}
    .attachment_meta_id{position: absolute;left:15px;bottom: 33px;font-size: 12px;color: #fff;}
    </style>
  {/block}
    {block name="main-top"}
        
    {/block}

  {block name="main"}
  <div class="attachment-wrap">
      
    <!--此页面主体内容-->
    <div class="row mt-10">
        
      <div class="col-xs-9 col-sm-9 button-list clearfix">   
         <div class="col-xs-3 col-sm-3 form-group pr-0">
             <span id="web_uploader_wrapper_attachmentIndex" class="btn btn-info btn-raised btn-sm">
                 <i class="fa fa-cloud-upload"></i> 上传图片
             </span>
             <span id="web_uploader_wrapper_attachmentFile" class="btn btn-info btn-raised btn-sm">
                 <i class="fa fa-cloud-upload"></i> 上传文件
             </span>
         &nbsp;&nbsp;<span class="btn btn-default btn-sm" id="media_batch">批量操作</span></div>
           <div class="col-xs-9 col-sm-9">
           <form id="selectForm" method="get" action="{:url('index')}" class="form-choice-url-param form-horizontal">
              <div class="form-group">
              <label for="media_type" class="fl control-label">类型:</label>
              <div class="col-md-2 pl-5 pr-5">                                                
                <select name="media_type" class="form-control">
                  <option value="0">选择类型</option>
                  {php}$media_type = input('get.media_type');{/php}
                  {volist name="mediaTypeList" id="mediaType"}
                      <option value="{$key}" {eq name="key" value="media_type"}selected{/eq}>{$mediaType}</option>
                  {/volist}
                </select>
                </div>

                <div class="col-md-4 pl-0 pr-5 has-feedback">
                  <input id="choice_date_range" class="form-control pr30" type="text" value="" placeholder="选择日期" name="choice_date_range">
                 <span class="fa fa-calendar form-control-feedback" style="right:5px;"></span>
                </div>

                <label for="term_id"  class="fl control-label">分类:</label>
                <div class="col-md-3">
                  <select name="term_id" class="form-control">
                    <option value="0">全部分类</option>
                    {volist name="media_cats" id="media_cat"}
                        {php}$term_id = input('get.term_id');{/php}
                        <option value="{$media_cat.term_id}" {eq name="media_cat.term_id" value="$term_id"}selected{/eq}>{$media_cat.name}</option>
                    {/volist}
                  </select>
                </div>
               <span class="btn btn-info btn-sm" id="choiceForm">筛选</span>
               
            </div>
            </form>
            </div>
         </div>
          <!--搜索-->
          <div class="col-xs-3 col-sm-3 clearfix">
              <form class="form" method="get" action="{:url('admin/attachment/index')}">
                  <div class="form-group">
                      <div class="input-group search-form">
                          <input type="text" name="keyword" class="search-input form-control" value="{$_GET.keyword|default=""}" placeholder="请输入名称">
                          <span class="input-group-btn"><button type="button" class="btn btn-default search-btn"><i class="fa fa-search"></i></button></span>
                      </div>
                  </div>
              </form>
          </div>
          <!--高级工具-->
          <div class="col-xs-10 col-sm-10 mb-15 ml-15" id="more-method">
             <label class="checkbox-toggle color-6 mr-10"><input class="check-all" type="checkbox"> 全选</label><a target-form="ids" class="btn btn-info btn-sm" onclick="move()"><i class="fa fa-exchange"></i> 修改分类</a>&nbsp;<a title="批量删除" target-form="ids" class="btn btn-danger ajax-post confirm btn-sm" model="attachment" href="{:url('attachment/setStatus',['status'=>'delete','model'=>'attachment'])}">批量删除</a>&nbsp;
          </div>
    </div>
      <hr/>
      {notempty name="attachment_list_data"}
    <div class="row mt-20 ml0 mr0">
    <ul class="attachment_list">
       {volist name="attachment_list_data" id="row"}
         <li class="col-sm-6 col-md-2 col-lg-2 mb-20" data-id="{$row.id}" >
            <div class="box-style">
              <div class="thumbnail">   
                <div class="centered tc">     
                    <img src="{$row.thumb_src}" alt="" >
                    <span class="attachment_meta_id fl">[{$row.id}]</span>
                </div>
              </div>
              <div class="attachment-foot">
                 <span><input type="checkbox" class="ids" name="ids[]" value="{$row.id}"></span><span class="disline oh f13 color-5 file-name">{$row.name}</span><span class="meta-ext">{$row.ext}</span>
              </div>
            </div>
          </li>
      {/volist}
      </ul>      
  </div>
  {else/}
  <p class="text-center">暂无结果</p>
  {/notempty}
  <div class="tc">{$table_data_page}</div>
  <!-- Modal Structure -->

</div>
<div class="modal fade mt100" id="moveModal">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">关闭</span></button>
                <p class="modal-title">移动至</p>
            </div>
            <div class="modal-body">
                <form action="{:url('moveCategory')}" method="post" class="form-move">
                    <div class="form-group">
                        <select name="to_cid" class="form-control">
                          {php}$input_media_cat = input('get.media_cat');{/php}
                          {volist name="media_cats" id="media_cat"}
                            <option value="{$media_cat.term_id}" {eq name="media_cat.term_id" value="$input_media_cat"}selected{/eq}>{$media_cat.name}</option>
                          {/volist}
                        </select>
                    </div>
                    <div class="form-group">
                        <input type="hidden" name="ids">
                        <input type="hidden" name="from_cid" value="{$cid|default='0'}">
                        <button class="btn btn-primary btn-block submit ajax-post" type="submit" target-form="form-move">确 定</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
{/block}

{block name="script"}
<script type="text/javascript" src="__LIBS__/daterangepicker/moment.min.js"></script>
<script type="text/javascript" src="__LIBS__/daterangepicker/daterangepicker.js"></script>

<script type="text/javascript" src="__LIBS__/webuploader/js/webuploader.min.js"></script>
<script type="text/javascript">
    //Date range picker
    $('#reservation').daterangepicker();
    //Date range picker with time picker
    $('#reservationtime').daterangepicker({timePicker: true, timePickerIncrement: 30, format: 'MM/DD/YYYY h:mm A'});
    //Date range as a button
    $('#choice_date_range').daterangepicker(
        {
          ranges: {
            '今天': [moment(), moment()],
            '昨天': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            '最近7天': [moment().subtract(6, 'days'), moment()],
            '最近30天': [moment().subtract(29,'days'), moment()],
          },
          startDate: moment().subtract(29, 'days'),
          endDate: moment()
        },
        function (start, end) {
          $('#choice_date_range').val(start.format('YYYY/MM/DD') + '—' + end.format('YYYY/MM/DD'));
        }
    );
     /*弹窗*/
    $(function () {
        var upload_attachmentIndex  = WebUploader.create({
            // 选完文件后，是否自动上传。
            auto: true,
            // swf文件路径
            swf: '__LIBS__/webuploader/Uploader.swf',
            // 文件接收服务端。
            server: "{:url('admin/Upload/upload',['path_type'=>$path_type,'type'=>'picture'])}",
            fileNumLimit: 10,
            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
            compress: false,
            // 验证单个文件大小是否超出限制, 超出则不允许加入队列
            fileSingleSizeLimit:{php}echo intval(config('attachment_options.image_max_size'))?:2*1024*1024;{/php},
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: {'id': "#web_uploader_wrapper_attachmentIndex", 'multi': false},
            accept:{title:'Image',extensions:'{:config('attachment_options.image_exts')}',mimeTypes:'image/*'}
        });
        // 当有文件添加进来的时候
        upload_attachmentIndex.on( 'fileQueued', function( file ) {
            $("ul.attachment_list").prepend('<li class="col-sm-6 col-md-2 col-lg-2 mb-20" id="'+file.id+'"><div class="box-style oh" style="height:160px;"><div class="progress progress-striped active" style="display: block;margin-top:41%;"><div class="progress-bar" role="progressbar" style="width: 100%;"></div></div><div class="attachment-foot"><p class="state"></p></div></div></li>');
        })
        // 文件上传过程中创建进度条实时显示。
        upload_attachmentIndex.on( 'uploadProgress', function( file, percentage ) {
            var $li = $( '#'+file.id ),
                $percent = $li.find('.progress .progress-bar');

            // 避免重复创建
            if ( !$percent.length ) {
                $percent = $('<div class="progress progress-striped active">' +
                    '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                    '</div>' +
                    '</div>').appendTo( $li ).find('.progress-bar');
            }

            $li.find('p.state').text('上传中');

            $percent.css( 'width', percentage * 100 + '%' );
        });
        /*上传成功*/
        upload_attachmentIndex.on('uploadSuccess', function (file, result) {
            if(result.code==1){
                var data = result.data;
                if (data.already==1) {
                    $( '#'+file.id ).remove();
                    showAttachmentInfo(data.id);//存在同个文件直接显示附件信息
                    $('#attachmentInfoModal').modal('show');
                    updateAlert(result.msg,'success');
                } else{
                    updateAlert(result.msg,'success');
                    window.location.href="{:url('index',['path_type'=>$path_type])}";
                }

            } else {
                updateAlert(result.msg);
            }
        });
        upload_attachmentIndex.on( 'uploadError', function( file ) {
            console.debug(file);
        });

        //上传文件
        var upload_attachmentFile  = WebUploader.create({
            // 选完文件后，是否自动上传。
            auto: true,
            // swf文件路径
            swf: '__LIBS__/webuploader/Uploader.swf',
            // 文件接收服务端。
            server: "{:url('admin/Upload/upload',['path_type'=>'file','type'=>'file'])}",
            fileNumLimit: 10,
            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
            compress: false,
            // 验证单个文件大小是否超出限制, 超出则不允许加入队列
            fileSingleSizeLimit:{php}echo intval(config('attachment_options.file_max_size'))?:2*1024*1024;{/php},
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: {'id': "#web_uploader_wrapper_attachmentFile", 'multi': false},
            accept:{title:'file',extensions:'{:config('attachment_options.file_exts')}',mimeTypes:'file/*'}

        });
        // 当有文件添加进来的时候
        upload_attachmentFile.on( 'fileQueued', function( file ) {
            $("ul.attachment_list").prepend('<li class="col-sm-6 col-md-2 col-lg-2 mb-20" id="'+file.id+'"><div class="box-style oh" style="height:160px;"><div class="progress progress-striped active" style="display: block;margin-top:41%;"><div class="progress-bar" role="progressbar" style="width: 100%;"></div></div><div class="attachment-foot"><p class="state"></p></div></div></li>');
        })
        // 文件上传过程中创建进度条实时显示。
        upload_attachmentFile.on( 'uploadProgress', function( file, percentage ) {
            var $li = $( '#'+file.id ),
                $percent = $li.find('.progress .progress-bar');

            // 避免重复创建
            if ( !$percent.length ) {
                $percent = $('<div class="progress progress-striped active">' +
                    '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                    '</div>' +
                    '</div>').appendTo( $li ).find('.progress-bar');
            }

            $li.find('p.state').text('上传中');

            $percent.css( 'width', percentage * 100 + '%' );
        });
        /*上传成功*/
        upload_attachmentFile.on('uploadSuccess', function (file, result) {
            if(result.code==1){
                var data = result.data;
                if (data.already==1) {
                    $( '#'+file.id ).remove();
                    showAttachmentInfo(data.id);//存在同个文件直接显示附件信息
                    $('#attachmentInfoModal').modal('show');
                    updateAlert(result.msg,'success');
                } else{
                    updateAlert(result.msg,'success');
                    window.location.href="{:url('index',['path_type'=>$path_type])}";
                }

            } else {
                updateAlert(result.msg);
            }
        });
        upload_attachmentFile.on( 'uploadError', function( file ) {
            console.debug(file);
        });

        //模态框内容
        $(".attachment_list li").click(function () {
            var $this = $(this);
            var attachmentId = $this.attr('data-id');
            showAttachmentInfo(attachmentId);//显示附件信息
          })

          //筛选应用触发表单提交
        $('#choiceForm').click(function(){
            $('#selectForm').submit();
        }); 
        //批量操作
        $('#media_batch').click(function(){
            $('#more-method').toggle();
        }); 

        //筛选
      $(document).on('submit', '.form-choice-url-param', function(e){
            //e.preventDefault();
            var seperator = "&";
            var form      = $(this).serialize();
            var action    = $(this).attr('action');
            if(action == ''){
                action = location.href;
            }
            var new_location = action+'?' + seperator + form;
            location.href = new_location;

            return false;
        });

        //icheck
        $('input').iCheck({
              checkboxClass:'icheckbox_minimal-blue',
              radioClass:'iradio_minimal-blue',
              increaseArea:'20%' // optional
        });
        $(".checkbox-toggle,.check-all").click(function () {
              var clicks = $(this).data('clicks');
              if (clicks) {
                //Uncheck all checkboxes
                $("input[type='checkbox']").iCheck("uncheck");
                $(".fa", this).removeClass("fa-check-square-o").addClass('fa-square-o');
              } else {
                //Check all checkboxes
                $("input[type='checkbox']").iCheck("check");
                $(".fa", this).removeClass("fa-square-o").addClass('fa-check-square-o');
              }
              $(this).data("clicks", !clicks);
        });
        $(".checkbox-toggle .iCheck-helper").click(function () {
              var all_checked=$('.checkbox-toggle>div.icheckbox_minimal-blue').hasClass('checked');
              if (!all_checked) {
                $("input[type='checkbox']").iCheck("uncheck");
              } else{
                $("input[type='checkbox']").iCheck("check");
              }
          });
    });   
    
    /**
     * 更新模态框附件信息
     * @param  {[type]} attachmentId [description]
     * @date   2018-02-16
     * @author 心云间、凝听 <981248356@qq.com>
     */
    function showAttachmentInfo(attachmentId){
        parent.layer.open({
            type: 2,
            title: '附件信息',
            shadeClose: true,
            shade: 0.8,
            area: ['620px','460px'],
            content: url('admin/Attachment/info',['id='+attachmentId]), 
            btn: ['提交','关闭'],
            yes: function(index, layero){
                var p_layer = parent.layer;
                var alt = p_layer.getChildFrame('#alt', index).val();
                  var term_id = p_layer.getChildFrame('#file-termid', index).val();
                  $.post(url("admin/Attachment/edit"),{id:attachmentId,alt:alt,term_id:term_id},function(result){
                      if (result.code==1) {
                        parent.updateAlert(result.msg,'success');
                        p_layer.closeAll();
                      } else{
                        parent.updateAlert(result.msg,'success');
                        
                      }
                  });
            }
        });
    }
      
    //移动分类
    function move(){
          var ids = '';
          $('input[name="ids[]"]:checked').each(function(){
             ids += ',' + $(this).val();
          });
          if(ids != ''){
              ids = ids.substr(1);
              $('input[name="ids"]').val(ids);
              $('.modal-title').html('移动选中的的附件至：');
              $('#moveModal').modal('show', 'fit')
          }else{
              updateAlert('请选择需要移动的附件', 'warning');
          }
      }
  </script>

  {/block}